<?php

namespace app\admin\controller\knscy;

use app\admin\model\KnscyInfos;
use app\admin\model\KnscyTicketsPrice;
use app\common\controller\AdminController;
use app\common\service\TicketPriceService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\Collection;
use think\facade\Db;
use think\facade\View;

/**
 * @ControllerAnnotation(title="knscy_tickets")
 */
class Tickets extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\KnscyTickets();

        $this->assign('getStatusList', $this->model->getStatusList());
        $this->assign('getNeedCheckList', $this->model->getNeedCheckList());
        $this->assign('getCanRefundList', $this->model->getCanRefundList());

    }
    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'title|标题' => 'require',
                'sub_title|副标题' => 'require',
                'price|价格' => 'require',
            ];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
                //处理动态价格
                KnscyTicketsPrice::where('ticket_id', $post['ticket_id'])
                    ->update(['ticket_id' => $this->model->id]);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'title|标题' => 'require',
                'sub_title|副标题' => 'require',
                'price|价格' => 'require',
            ];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }

        $this->assign('row', $row);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="价格设置")
     */
    public function dynamicPrice()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $model = new KnscyTicketsPrice();
            //删除一个记录
            if(isset($post['is_delete']) && $post['is_delete'] == 1){
                KnscyTicketsPrice::where( 'id' ,$post['id'] )->delete();
                $this->success('删除成功', $this->getList($model, $post['ticket_id']) );
            }
            //排序修改 is_sort
            if(isset($post['is_sort']) && $post['is_sort'] == 1){
                KnscyTicketsPrice::where( 'id' ,$post['id'] )->update(['sort'=>$post['sort']]);
                $this->success('排序成功', $this->getList($model, $post['ticket_id']) );
            }
            //编辑的时候加载列表
            if(isset($post['is_edit']) && $post['is_edit'] == 1){
                $this->success('成功', $this->getList($model, $post['ticket_id']) );
            }
            //保存新增
            $rule = [
                'type_id|类型' => 'require',
                'ticket_id|ID' => 'require',
                'content|价格项目' => 'require',
                'price|价格' => 'require',
            ];

            $this->validate($post, $rule);
            try {

                $save = $model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            if ($save) {

                $this->success('保存成功', $this->getList($model, $post['ticket_id']) );
            } else {
                $this->error('保存失败');
            }
        }

    }

    /**
     * 获取当前动态价格的记录
     * @param $model
     * @param $ticket_id
     * @return array
     */
    protected  function getList($model, $ticket_id)
    {
        //清理昨天产生的未保存数据
        KnscyTicketsPrice::where([
            ['ticket_id', '>', 999999999],
            ['ticket_id', '<', strtotime('-1 hours')]
        ])->delete();
        //活动价格列表
        $list = KnscyTicketsPrice::where('ticket_id', $ticket_id)
            ->order(Db::raw('sort=0, sort asc,id desc'))
            ->select()->each(function ($item) {});
        $this->app->view->engine()->layout('layout/empty');
        $types = $model->getTypeIdList();
        $html = $this->fetch('knscy/tickets/dynamic_price',
            [
                'priceList' => $list,
                'types' => $types,
            ]);

        $day =date('Y-m-01' ); //本月第一天
        return ['html'=>$html,'price'=> TicketPriceService::getMonthPriceList($day, $ticket_id)];
    }
    /**
     * @NodeAnotation(title="门票关联文案")
     */
    public function infos()
    {
        $name = $this->request->get('name');
        $ks = $this->request->get('ks');
        $page = $this->request->get('page', 1, 'intval');
        $where = [];
        $whereOr = [];

        if ($name) {
            $where[] = ['title', 'like', '%' . $name . '%'];
        }
        $field = 'id,title';
        $order = 'id asc';

        $selected_data = [];
        if ($ks && $page == 1) {
            $whereOr[] = ['id', '=', $ks];
            $selected_data = KnscyInfos::where($whereOr)
                ->where('status',1)
                ->field($field)
                ->select()
                ->toArray();
            $where[] = ['id', '<>', $ks];
        }

        $list = KnscyInfos::where($where)
            ->where('status',1)
            ->field($field)
            ->order($order)
            ->paginate(10);
        $pageData = $list->toArray();
        if (!$list->isEmpty()) {

            $arrData = $list->toArray()['data'];
            if (!empty($selected_data)) {
                $arrData = array_values(array_merge($arrData, $selected_data));
            }
            foreach ($arrData as &$item) {
                $name = $item['title'];
                $item['name'] = '[' . $item['id'] . '] ' . $name;

                $item['selected'] = false;
                if ($ks == $item['id']) {
                    $item['selected'] = true;
                }
                $item['value'] = $item['id'];
            }
            $pageData['data'] = $arrData;
        }

        $this->success('success', $pageData);
    }


}